<template>
  <div class="app-header" :style="{
      height: headerHeight + 'px',
      lineHeight: headerHeight + 'px',
      width: headerWidth,
      left: headerLeft + 'px'
    }">
    <div class="header-left">
      <div class="header-logo iconfont icon-arrowleft" @click="goBack"></div>
      <div class="header-logo iconfont icon-reload" @click="refresh"></div>
    </div>
    <div class="header-center">
      <span v-if="hasLogoImage">
        <img class="logoImage" :src="systemLogoImage" />
      </span>
      <span v-else>
        <!-- <img
          class="defaultLogoImage"
          src="../../assets/images/logo-liantong.png"
        /> -->
      </span>
      <template v-if="isBatteryCar">
        <div class="line"></div>
        <span>
          <img class="defaultLogoImage" src="../../assets/images/logo-zhijiangxilu.png" />
        </span>
      </template>
      <span>{{ systemName }}</span>
    </div>
    <div class="header-right">
      <div class="user-agreement" @click="handleAgreement">用户隐私协议</div>
      <div class="header-logo iconfont icon-ring" @click="alarmCount">
        <router-link :to="'/event/supervise'">
          <span class="show-alarm" v-show="hasAlarm">{{ showAlarmNum }}</span>
        </router-link>
      </div>
      <div style="display:none" class="header-logo iconfont icon-setting" @click="settings">
        <!-- <span class="show-alarm">123</span> -->
      </div>
      <div class="header-logo iconfont icon-ellipsis loginout-btn-wrap" @mouseenter="mouseEnter()" @mouseleave="mouseLeave()" @click="watchMore">
        <transition name="el-fade-in-linear">
          <div class="login-out-btn" v-show="isShow" @click="loginOut">
            退出
          </div>
        </transition>
      </div>
    </div>
    <el-dialog title="平台隐私政策" :visible.sync="isAgreement" center :modal-append-to-body="false" top="5vh" width="60%">
      <div class="dialog-body">
        <Agreement></Agreement>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import Agreement from './agreement.vue'

export default {
  name: 'appHeader',
  components: {
    Agreement
  },
  data () {
    return {
      isBatteryCar: false,
      isShow: false,
      headerHeight: this.$base.getConst('common', 'headerHeight'),
      headerLeft: this.$base.getConst('common', 'sidebarWidth'),
      headerWidth: 'calc(100% - ' + this.$base.getConst('common', 'sidebarWidth') + 'px)',
      showAlarmNum: '0',
      hasAlarm: false,
      timer: {}, // 缓存计时器，方便在组件销毁时清除
      roleDeptName: '',
      systemName: '',
      systemLogoImage: '',
      hasLogoImage: false,
      isAdmin: false,
      isAgreement: false
    }
  },
  computed: {
    ...mapState({
      resAlarmCount: state => state.event.alarmCount
    })
  },
  watch: {
    resAlarmCount (val) {
      this.getAlarmNum()
    }
  },
  mounted () {
    // 未登录时直接return
    if (this.$store.state.loginShow) {
      return
    }
    // this.initWebSocket()
    this.getAlarmNum()

    let userInfo = JSON.parse(this.$base.getSessionStorage('userInfo'))
    if (userInfo.chargeMenuFlag === '1') {
      this.isBatteryCar = true
    }

    let self = this
    this.timer = setInterval(() => {
      if (this.$store.state.loginShow) {
        clearInterval(this.timer)
        return
      }

      // this.getAlarmNum()

      // 断开重连机制,尝试发送消息,捕获异常发生时重连
      try {
        self.stompClient.send('test')
      } catch (err) {
        console.log('断线了: ' + err)
        // self.connection()
      }
    }, 1000 * 60)
    let userInfoRes = JSON.parse(this.$base.getSessionStorage('userInfo'))
    this.roleDeptName = userInfoRes ? userInfoRes.deptName : ''

    if (userInfoRes.systemLogoImage) {
      this.systemLogoImage = userInfoRes ? JSON.parse(userInfoRes.systemLogoImage) : ''
      this.hasLogoImage = true
    }
    let userRole = userInfoRes.userRole
    if (userRole === 1) {
      this.isAdmin = true
      this.roleDeptName = ''
    } else {
      this.roleDeptName = '('
      if (userInfoRes.deptName1) {
        self.roleDeptName += userInfoRes.deptName1
      }
      if (userInfoRes.deptName2) {
        self.roleDeptName += '-' + userInfoRes.deptName2
      }
      if (userInfoRes.deptName3) {
        self.roleDeptName += '-' + userInfoRes.deptName3
      }
      this.roleDeptName += ')'
    }
    this.systemName = userInfoRes.systemName ? userInfoRes.systemName : '智城精治-智能安防综合管理平台' + this.roleDeptName
    // 芷江西路演示临时改动
    // this.systemName = userInfoRes.systemName ? userInfoRes.systemName : '智城精治-芷江西路街道智能非机动车库' + this.roleDeptName
  },
  beforeDestroy: function () {
    // 页面离开时断开连接,清除定时器
    this.disconnect()
    clearInterval(this.timer)
  },
  methods: {
    initWebSocket () {
      this.connection()
    },
    connection () {
      let url = this.$base.getUrl('ws')
      // 建立连接对象
      this.socket = new SockJS(url)
      // 获取STOMP子协议的客户端对象
      this.stompClient = Stomp.over(this.socket)
      // 定义客户端的认证信息,按需求配置
      var headers = {
        login: 'mylogin',
        passcode: 'mypasscode',
        'client-id': 'my-client-id'
      }

      let userInfoRes = JSON.parse(this.$base.getSessionStorage('userInfo'))

      // 关闭websocket调试信息，如果注释下面3行代码，websocket调试信息会显示
      this.stompClient.debug = function (str) {
        // console.log(str)
      }

      // 向服务器发起websocket连接
      this.stompClient.connect(headers, (frame) => {
        // this.stompClient.subscribe('/alarm/test', (msg) => {
        //   console.log(msg.body)
        // })
        this.stompClient.subscribe('/user/' + userInfoRes.userId + '/event', (msg) => {
          console.log('恭喜你收到一条事件告警', JSON.parse(msg.body))
          // this.showAlarmNum = parseInt(this.showAlarmNum) + 1
          this.getAlarmNum()
        })
      }, (err) => {
        // 连接发生错误时的处理函数
        console.log(err)
      })
    },
    // 断开连接
    disconnect () {
      if (this.stompClient != null) {
        this.stompClient.disconnect()
        console.log('Disconnected')
      }
    },
    goBack: function () {
      this.$router.go(-1)
    },
    refresh: function () {
      window.location.reload()
    },
    settings: function () {

    },
    getAlarmNum: function () {
      let userInfoRes = JSON.parse(this.$base.getSessionStorage('userInfo'))
      let url = this.$base.getUrl('getCountByState')
      let params = {
        url: url,
        data: {
          'deptId': userInfoRes.deptId
        },
        noLoading: true
      }
      this.$store.dispatch('getForm', params).then((res) => {
        this.showAlarmNum = res
        this.hasAlarm = res > 0
      })
    },

    alarmCount: function () {
      this.$router.push({ name: 'eventSupervise' })
    },

    watchMore: function () {
      this.isShow = !this.isShow
    },

    loginOut: function () {
      // 隐藏退出按钮
      this.$data.isShow = false
      let _this = this
      let url = this.$base.getUrl('logout')

      this.$http({
        method: 'POST',
        url: url,
        headers: {
          'token': _this.$base.getSessionStorage('token')
        }
      }).then(function () {
        _this.$base.setSessionStorage('token', '')
        _this.$base.setLocalStorage('localToken', '')
        _this.$base.setLocalStorage('localUserInfo', '')
        _this.$base.setLocalStorage('hasRequestLoginApi', '')
        _this.$store.commit('changeLoginShow', true)

        // 页面离开时断开连接,清除定时器
        _this.disconnect()
        clearInterval(_this.timer)
      })
    },

    // 鼠标移入显示退出按钮
    mouseEnter () {
      this.isShow = true
    },
    // 鼠标离开隐藏退出按钮
    mouseLeave () {
      this.isShow = false
    },
    // 用户隐私协议
    handleAgreement () {
      this.isAgreement = true
    }

  }

}
</script>

<style>
.dialog-body {
  height: 75vh;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 20px;
}
.dialog-body::-webkit-scrollbar {
  width: 10px;
  height: 1px;
}
.dialog-body::-webkit-scrollbar-thumb {
  border-radius: 10px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #ededed;
}

.dialog-body::-webkit-scrollbar-track {
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  background: #535353;
}
.app-header .login-out-btn {
  position: absolute;
  top: 37px;
  right: -5px;
  z-index: 999;
  background: #fff;
  width: 80px;
  height: 36px;
  line-height: 36px;
  font-size: 14px;
  color: #111;
  text-align: center;
  border-radius: 3px;
  cursor: pointer;
  box-shadow: 1px 1px 5px #6d6d6d;
}
.app-header .loginout-btn-wrap {
  padding: 5px 8px 14px !important;
}

.app-header {
  position: fixed;
  z-index: 9;
  top: 0;
  display: flex;
  justify-content: space-between;
  width: 100%;
  background-color: #111;
  box-shadow: rgba(0, 0, 0, 0.1) 0 3px 12px;
  /*z-index: 100;*/
}

.app-header .header-left {
  font-size: 0;
}

.app-header .header-center {
  /* width: 450px; */
  text-align: center;
  font-size: 14px;
  color: #fff;
  display: flex;
  align-items: center;
}

.app-header .header-center .logoImage {
  width: auto;
  height: 32px;
  transform: translate(-10px, 8px);
}

.app-header .header-center .defaultLogoImage {
  width: auto;
  height: 32px;
  transform: translate(-10px, 8px);
}

.app-header .header-center .line {
  display: inline-block;
  height: 32px;
  width: 2px;
  background: white;
  margin-left: 6px;
  margin-right: 20px;
}

.app-header .header-right {
  float: right;
  margin-right: 10px;
  min-width: 130px;
  font-size: 0;
}
.header-right .user-agreement {
  font-size: 14px;
  color: #fff;
  display: inline;
}
.header-right .user-agreement:hover {
  cursor: pointer;
  color: rgba(255, 255, 255, 0.8);
}

.app-header .header-logo {
  position: relative;
  display: inline;
  top: 5px;
  margin-left: 25px;
  padding: 5px;
  font-size: 18px;
  cursor: pointer;
  color: #fff;
}

.app-header .header-message {
  position: relative;
}

.app-header .header-message:after {
  position: absolute;
  display: none;
  top: 0;
  right: -10px;
  content: '';
  padding: 4px;
  font-size: 0;
  background-color: #ff5722;
  border-radius: 100%;
}

.app-header .header-message.on:after {
  display: block;
}

.app-header .header-message:before {
  position: absolute;
  display: none;
  top: -15px;
  left: -10px;
  content: '';
  width: 40px;
  height: 3px;
  font-size: 0;
  background-color: #333;
}

.app-header .header-message.cur:before {
  display: block;
}

.show-alarm {
  padding: 0 5px;
  height: 16px;
  line-height: 18px;
  font-size: 14px;
  text-align: center;
  z-index: 99;
  position: absolute;
  background-color: red;
  border-radius: 8px;
  top: -4px;
  left: 13px;
  color: #fff;
}
</style>
